import pymongo ;
import os ;
import re ;
import datetime;
from pymongo import MongoClient;
import time
from PyQt4.QtCore import QObject
import ConfigParser, os
class KDBUtility(QObject):
	@staticmethod
	def GetCollectionName(country,market,isconsolidate=False):
		return country.upper()+"."+KDBUtility.__internalmarket(market).upper()+("" if isconsolidate==False else "_BYDATE")
	@staticmethod
	def GetMarketCountryByCollectionName(collection_name,isconsolidate=False):
		(country,market)=collection_name.split('.',2)
		if isconsolidate==True:
			(market,temp)=KDBUtility.__internalmarket(market).split('_',2)
		return (country,market)
	@staticmethod
	def IsSymbolBased(colname):
		if colname[-7:]=="_BYDATE":
			return True
		else:
			return False
	@staticmethod
	def GetProviderObject(ProviderName):
		## get {providername,objectname} dictonary
		m_dict={"EOD":"KEODProvider.KEODProvider","Stooq":"KStooqProvider.KStooqProvider"}
		return m_dict[ProviderName]
	@staticmethod
	def GetImportHistoryPath(provider):	
		config = ConfigParser.ConfigParser()
		config.readfp(open('Config.txt'))		
		return config.get('DB_General','HistoryRootPath')+config.get('DB_'+provider,'RelativePath')	
	@staticmethod
	def GetDailyUpdateFilePath():	
		config = ConfigParser.ConfigParser()
		config.readfp(open('Config.txt'))	
		dailypath=config.get('DB_General','DailyUpdateRootPath')
		if not os.path.exists(dailypath):
			os.makedirs(dailypath)
		onlyfiles = [ f for f in os.listdir(dailypath) if os.path.isfile(os.path.join(dailypath,f)) ]
		return onlyfiles[0]
	@staticmethod
	def OverrideExstingFileWhenDailyUpdate():
		config = ConfigParser.ConfigParser()
		config.readfp(open('Config.txt'))
		return config.get('DB_General','OverrideWhenUpdate')=='True'
	@staticmethod
	def GetDailyBackupPath(freq,country,market):	
		config = ConfigParser.ConfigParser()
		config.readfp(open('Config.txt'))	
		if freq=="Daily":
			backpath= config.get('DB_General','DailyBackUpRootPath')
		elif freq=="5Min":
			backpath= config.get('DB_General','5MinBackUpRootPath')			
		backpath+=r'/'+country.upper()+r'/'+KDBUtility.__internalmarket(market).upper()
		if not os.path.exists(backpath):
			os.makedirs(backpath)		
		return backpath
	@staticmethod
	def __internalmarket(outmarket):
		# get the internal market name since differnt provider may have differnt naming convention
		if outmarket.upper()=='AMEX':
			return 'NYSEMKT'
		else:
			return outmarket
		
		

